package com.rent.auth.config;

import com.rent.common.config.BaseConfig;
import com.security.config.JwtConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;

/**
 * @Author zhang
 * @create 2022/3/26 17:18
 */
@Slf4j
@Configuration
public class BeanConfig extends BaseConfig {

    @Autowired
    private JwtConfig jwtConfig;

    // http请求调用Bean
    @Bean(name = "restTemplate")
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    // 自定义授权转换器
    @Bean
    public CustomUserAuthenticationConverter userAuthenticationConverter() {
        return new CustomUserAuthenticationConverter();
    }


    /****
     * JWT令牌转换器
     * @return 结果
     */
    @Bean
    public CustomJwtAccessTokenConverter jwtAccessTokenConverter() {
        CustomJwtAccessTokenConverter converter = new CustomJwtAccessTokenConverter();
        // 设置签名
        String key = getKey();
        log.info("签名的key:{}", key);
        converter.setSigningKey(key);
//        converter.setVerifierKey(key);
        //配置自定义的CustomUserAuthenticationConverter
        DefaultAccessTokenConverter accessTokenConverter = (DefaultAccessTokenConverter) converter.getAccessTokenConverter();
        accessTokenConverter.setUserTokenConverter(userAuthenticationConverter());
        converter.setAccessTokenConverter(accessTokenConverter);
        return converter;
    }

    /***
     * 定义JwtTokenStore
     */
    @Bean
    public TokenStore tokenStore() {
        log.info("创建token转换器");
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /**
     * 加密key
     *
     * @return key
     */
    private String getKey() {
        byte[] encodedKey = Base64.getEncoder().encode(jwtConfig.getSecret().getBytes());
        return new String(encodedKey);
    }


}
